package com.bookstore.Controller;

import com.bookstore.Domain.Code;
import com.bookstore.Domain.Result;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author 未来
 */
@CrossOrigin
@Controller
@RequestMapping("/images")
public class ImagesController {

    /**
     * 根据图片资源添加到相关的资源文件
     * @return ：是否添加成功
     */
    @PostMapping
    @ResponseBody
    public String postBookImages(@RequestParam("file") MultipartFile file) throws IOException {
        String resources = "";
        // 保存图片文件到本地
        String fileName = file.getOriginalFilename();
        //获取当前在本机的工作目录路径
        String property = System.getProperty("user.dir");
        // 获取最后一个"."的位置
        int lastIndexOfDot = fileName.lastIndexOf(".");
        // 获取文件后缀名
        String suffix = fileName.substring(lastIndexOfDot + 1);
        if ("png".equals(suffix) || "gif".equals(suffix) || "jpg".equals(suffix) || "jpeg".equals(suffix)) {
            resources = "\\src\\main\\resources\\static\\images\\";
        } else if ("txt".equals(suffix)) {
            resources = "\\src\\main\\resources\\static\\text\\";
        }
        //存放txt资源目录
        String destPath = property + resources + fileName;
        File dest = new File(destPath);
        if (dest.exists()) {
        } else {
            file.transferTo(dest);
        }
        return "http://localhost:8023/images/"+fileName;
    }
}
